package controllers.manage.curriculum;

import controllers.BaseController;
import controllers.auth.Secure;
import helper.GlobalConfig;
import jodd.util.StringUtil;
import models.constants.DeletedStatus;
import models.merchant.Merchant;
import models.venue.curriculum.CurriculumType;
import play.modules.paginate.JPAExtPaginator;
import play.mvc.Controller;
import play.mvc.With;

import java.util.HashMap;
import java.util.Map;

/**
 * 课程类型管理
 * Created by hanbin on 17/5/23.
 */
@With(BaseController.class)
public class CurriculumTypeCtrl extends Controller {

    /**
     * 跳转到课程类型管理页面
     */
    public static void index(Integer pageNumber, String typeName){

        Merchant merchant = Secure.getLoginUser().merchant;

        pageNumber = pageNumber == null ? 1 : pageNumber;
        Map<String , Object> searchMap = new HashMap<>();

        if(StringUtil.isNotBlank(typeName)) {
            searchMap.put("typeName", "%"+typeName+"%");
        }

        if(merchant != null){
            searchMap.put("merchantId", merchant.id);
        }

        flash.put("menuId", "11");

        JPAExtPaginator<CurriculumType> resultPage = CurriculumType.findByCondition(searchMap, "id desc", pageNumber, GlobalConfig.PAGE_SIZE);
        render(resultPage, pageNumber, typeName);
    }

    /**
     * 跳转到新增课程类型页面
     */
    public static void add(){
        render();
    }

    /**
     * 跳转到修改课程类型页面
     */
    public static void modify(long id, Integer pageNumber){
        CurriculumType curriculumType = CurriculumType.findById(id);
        render(curriculumType, pageNumber);
    }


    /**
     * 创建课程类型
     */
    public static void create(CurriculumType curriculumType){

        Merchant merchant = Secure.getLoginUser().merchant;
        curriculumType.merchant = merchant;

        curriculumType.deleted = DeletedStatus.UN_DELETED;
        curriculumType.save();
        flash.put("msg" , "课程类型创建成功");
        redirect("/BS0015/admin/curriculumType/index/1");
    }

    /**
     * 修改课程类型
     */
    public static void update(Long id, CurriculumType curriculumType, Integer pageNumber){
        CurriculumType.update(id , curriculumType);
        flash.put("msg" , "课程类型修改成功");
        redirect("/BS0015/admin/curriculumType/index/"+pageNumber);
    }

    /**
     * 删除课程类型
     */
    public static void delete(long id , Integer pageNumber){
        pageNumber = pageNumber == null ? 1 : pageNumber;
        CurriculumType curriculumType = CurriculumType.findById(id);
        //判断类型是否被使用
        if(CurriculumType.checkIsUsed(id)){
            flash.put("msg" , "课程类型正在被使用,无法删除");
            redirect("/BS0015/admin/curriculumType/index/"+pageNumber);
        }

        curriculumType.deleted= DeletedStatus.DELETED;
        curriculumType.save();
        flash.put("msg" , "课程类型删除成功");
        redirect("/BS0015/admin/curriculumType/index/"+pageNumber);
    }

}
